package com.jee.ssm.common.socket.rescue;

import java.util.Collection;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;

import com.jee.ssm.common.config.Const;
import com.jee.ssm.model.Account;

public class RescueInterceptor extends HttpSessionHandshakeInterceptor {

	@Override
	public Collection<String> getAttributeNames() {
		return super.getAttributeNames();
	}

	@Override
	public void setCopyAllAttributes(boolean copyAllAttributes) {
		super.setCopyAllAttributes(copyAllAttributes);
	}

	@Override
	public boolean isCopyAllAttributes() {
		return super.isCopyAllAttributes();
	}

	@Override
	public void setCopyHttpSessionId(boolean copyHttpSessionId) {
		super.setCopyHttpSessionId(copyHttpSessionId);
	}

	@Override
	public boolean isCopyHttpSessionId() {
		return super.isCopyHttpSessionId();
	}

	@Override
	public void setCreateSession(boolean createSession) {
		super.setCreateSession(createSession);
	}

	@Override
	public boolean isCreateSession() {
		return super.isCreateSession();
	}

	@Override
	public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
		Account account = (Account) getSession(request).getAttribute(Const.ACCOUNT);
        attributes.put(Const.WEBSOCKET_ID,account.getId());
		return super.beforeHandshake(request, response, wsHandler, attributes);
	}

	@Override
	public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception ex) {
		super.afterHandshake(request, response, wsHandler, ex);
	}
	
	/**
     * 用来获取session
     * @param request 请求
     * @return session
     */
    private HttpSession getSession(ServerHttpRequest request) {
        if(request instanceof ServletServerHttpRequest) {
            ServletServerHttpRequest serverRequest = (ServletServerHttpRequest)request;
            return serverRequest.getServletRequest().getSession(this.isCreateSession());
        } else {
            return null;
        }
    }

	
	
}
